package com.zhhtech.zhh.ui.helper

import android.content.Context
import android.view.View
import androidx.core.content.ContextCompat
import com.alibaba.fastjson.JSON
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.view.OptionsPickerView
import com.bigkoo.pickerview.view.TimePickerView
import com.zhhtech.zhh.ui.R
import com.zhhtech.zhh.ui.utils.Logger
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.util.*
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

object PickerViewHelper {
    private var cityOptions1Items: ArrayList<com.zhhtech.zhh.ui.bean.picker.BaseCityBean> = ArrayList()
    private val cityOptions2Items: ArrayList<List<com.zhhtech.zhh.ui.bean.picker.BaseCityBean>> = ArrayList()
    private val cityOptions3Items: ArrayList<List<List<com.zhhtech.zhh.ui.bean.picker.BaseCityBean>>> = ArrayList()
    fun getCityOptions1ByPosition(position: Int) = cityOptions1Items[position]
    fun getCityOptions2ByPosition(option1: Int, option2: Int) = cityOptions2Items[option1][option2]
    fun getCityOptions3ByPosition(option1: Int, option2: Int, option3: Int) = cityOptions3Items[option1][option2][option3]

    fun builderPicker(context: Context, optionsPickerBuilder: OptionsPickerBuilder): OptionsPickerBuilder {
        optionsPickerBuilder.setTitleBgColor(ContextCompat.getColor(context, R.color.bg))
            .setTitleColor(ContextCompat.getColor(context, R.color.text_color)).setTitleSize(15).setSubCalSize(15)
            .setBgColor(ContextCompat.getColor(context, R.color.white))
            .setSubmitColor(ContextCompat.getColor(context, R.color.main_color))
            .setCancelColor(ContextCompat.getColor(context, R.color.text_hint_color_2))
            .setBgColor(ContextCompat.getColor(context, R.color.white))
            .setDividerColor(ContextCompat.getColor(context, R.color.line)).setTextColorCenter(ContextCompat.getColor(context, R.color.text_color))
            .setTextColorOut(ContextCompat.getColor(context, R.color.text_hint_color_2)).setContentTextSize(16)
            .setLineSpacingMultiplier(2f).setDividerColor(ContextCompat.getColor(context, R.color.bg))
        return optionsPickerBuilder
    }

    fun createTimePicker(context: Context, title: String, success: ((date: Date, view: View) -> Unit)?): TimePickerView {
        return TimePickerBuilder(context, success).setType(booleanArrayOf(true, true, true, false, false, false)) // 默认全部显示
            .setTitleBgColor(ContextCompat.getColor(context, R.color.bg)).setTitleColor(ContextCompat.getColor(context, R.color.text_color))
            .setTitleSize(15).setSubCalSize(15)
            .setBgColor(ContextCompat.getColor(context, R.color.white))
            .setSubmitColor(ContextCompat.getColor(context, R.color.main_color))
            .setCancelColor(ContextCompat.getColor(context, R.color.text_hint_color_2))
            .setBgColor(ContextCompat.getColor(context, R.color.white))
            .setDividerColor(ContextCompat.getColor(context, R.color.line)).setTextColorCenter(ContextCompat.getColor(context, R.color.text_color))
            .setTextColorOut(ContextCompat.getColor(context, R.color.text_hint_color_2)).setContentTextSize(16)
            .setLineSpacingMultiplier(2f).setDividerColor(ContextCompat.getColor(context, R.color.bg)).setTitleText(title) //标题文字
            .isCyclic(true) //是否循环滚动
            .setDate(Calendar.getInstance()) // 如果不设置的话，默认是系统时间*/
//            .setRangDate(startDate, endDate) //起始终止年月日设定
            .setLabel("年", "月", "日", "时", "分", "秒") //默认设置为年月日时分秒
            .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
            .build()
    }

    suspend fun createProvCityAreaPickerView(
        context: Context,
        title: String = "选择城市",
        option1: Int = 0,
        option2: Int = 0,
        option3: Int = 0,
        mOnOptionsSelectListener: ((Int, Int, Int) -> Unit)? = null,
        success: ((OptionsPickerView<com.zhhtech.zhh.ui.bean.picker.BaseCityBean>) -> Unit)? = null,
    ) {
        loadProvData()
        success?.invoke(doCreateProvCityAreaPickerView(context, title, option1, option2, option3, mOnOptionsSelectListener))
    }

    private fun doCreateProvCityAreaPickerView(
        context: Context,
        title: String,
        selectOption1: Int,
        selectOption2: Int,
        selectOption3: Int,
        mOnOptionsSelectListener: ((Int, Int, Int) -> Unit)? = null,
    ): OptionsPickerView<com.zhhtech.zhh.ui.bean.picker.BaseCityBean> {
        // 弹出选择器
        val pvOptions: OptionsPickerView<com.zhhtech.zhh.ui.bean.picker.BaseCityBean> =
            builderPicker(context, OptionsPickerBuilder(context) { option1, option2, option3, _ ->
                mOnOptionsSelectListener?.invoke(option1, option2, option3)
            }).setTitleText(title).setSubmitText(context.getString(R.string.button_confirm)).setCancelText(context.getString(R.string.button_cancel))
                .setSelectOptions(selectOption1, selectOption2, selectOption3).build()
        pvOptions.setPicker(cityOptions1Items, cityOptions2Items, cityOptions3Items) //三级选择器
        return pvOptions
    }

    private fun doCreateProvCityPickerView(
        context: Context,
        title: String,
        selectOption1: Int,
        selectOption2: Int,
        mOnOptionsSelectListener: ((Int, Int) -> Unit)? = null,
    ): OptionsPickerView<com.zhhtech.zhh.ui.bean.picker.BaseCityBean> {
        // 弹出选择器
        val pvOptions: OptionsPickerView<com.zhhtech.zhh.ui.bean.picker.BaseCityBean> =
            builderPicker(context, OptionsPickerBuilder(context) { option1, option2, _, _ ->
                mOnOptionsSelectListener?.invoke(option1, option2)
            }).setTitleText(title).setSubmitText(context.getString(R.string.button_confirm)).setCancelText(context.getString(R.string.button_cancel))
                .setSelectOptions(selectOption1, selectOption2)
                .build()
        pvOptions.setPicker(cityOptions1Items, cityOptions2Items) //三级选择器
        return pvOptions
    }

    private suspend fun loadProvData() = suspendCoroutine<Unit> { coroutine ->
        if (cityOptions1Items.isEmpty()) {
            val stringBuilder = StringBuilder()
            try {
                val assetManager = com.zhhtech.zhh.ui.AppCore.app.assets
                val bf = BufferedReader(InputStreamReader(assetManager.open("prov_city.json")))
                var line: String?
                while (bf.readLine().also { line = it } != null) {
                    stringBuilder.append(line)
                }
            } catch (e: IOException) {
                Logger.e(e)
                stringBuilder.clear()
                stringBuilder.append("[]")
            }
            val provBeans = JSON.parseArray(stringBuilder.toString(), com.zhhtech.zhh.ui.bean.picker.ProvBean::class.java) ?: ArrayList()
//                val provBeans = MoshiUtils.parseArray(provsStr, ProvBean::class.java) ?: ArrayList()
            provBeans.forEach {
                cityOptions1Items.add(it)
                val cityList = ArrayList<com.zhhtech.zhh.ui.bean.picker.CityBean>() //该省的城市列表（第二级）
                val provinceAreaList = ArrayList<ArrayList<com.zhhtech.zhh.ui.bean.picker.CounBean>>() //该省的所有地区列表（第三极）
                it.city.forEach {
                    cityList.add(it)
                    val cityAreaList = ArrayList<com.zhhtech.zhh.ui.bean.picker.CounBean>() //该城市的所有地区列表
                    it.coun.forEach { cityAreaList.add(it) }
                    provinceAreaList.add(cityAreaList)
                }
                cityOptions2Items.add(cityList)
                cityOptions3Items.add(provinceAreaList)
            }
            coroutine.resume(Unit)
        } else {
            coroutine.resume(Unit)
        }
    }
}

